package com.lee.utils;

import java.sql.*;
import java.util.*;

/**
 * @author lee
 */
public class HiveJdbcUtil {

    private static String url = PropertiesUtil.getValue("hive.jdbc.url");
    private static String username = PropertiesUtil.getValue("hive.jdbc.user");
    private static String password = PropertiesUtil.getValue("hive.jdbc.password");

    static {
        try {
            Class.forName("org.apache.hive.jdbc.HiveDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static HashMap<String, List<String>> getAllTableList() throws Exception {

        Connection conn = getConnection();
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("show databases");

        // 获取所有数据库
        ArrayList<String> allDatabases = new ArrayList<>();
        List<String> databaseFromPro = HiveJdbcUtil.getDatabaseFromPro();

        if (databaseFromPro.size() != 0) {
            // 集合元素复制到另外一个集合
            allDatabases.addAll(databaseFromPro);
        } else {
            while (rs.next()) {
                allDatabases.add(rs.getString(1));
            }
        }

        allDatabases.removeAll(HiveJdbcUtil.getExcludeDbList());
        HashMap<String, List<String>> all = new HashMap<>();
        for (String db : allDatabases) {
            conn.createStatement().execute("use " + db);
            ResultSet showTables = conn.createStatement().executeQuery("show tables");
            ArrayList<String> tablesList = new ArrayList<>();
            while (showTables.next()) {
                tablesList.add(showTables.getString(1));
            }
            all.put(db, tablesList);
        }
        return all;
    }

    public static List<String> getDatabaseFromPro() {
        String database = PropertiesUtil.getValue("database");
        if (database.isEmpty()) {
            return Collections.emptyList();
        }
        return Arrays.asList(database.split(","));
    }

    public static List<String> getExcludeDbList() {
        String database = PropertiesUtil.getValue("db.exclude");
        if (database.isEmpty()) {
            return Collections.emptyList();
        }
        return Arrays.asList(database.split(","));
    }
}